/**
 * 
 */
package cream.alarm.helper.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import cream.alarm.R;
import cream.alarm.db.DbAdapter;
import cream.alarm.helper.WeekdayHelper;
import cream.alarm.model.Weekday;
import cream.alarm.util.DateUtil;

/**
 * @author Cream
 * @since 1.0 2012-01-23
 */
public class WeekdayHelperImpl implements WeekdayHelper {

	private final DbAdapter dbAdapter;

	public WeekdayHelperImpl(Context ctx) {
		this.dbAdapter = new DbAdapter(ctx);
	}

	@Override
	public boolean isWeekday(Date date) {
		dbAdapter.open();
		try {
			Weekday weekday = dbAdapter.fetchWeekday(date);
			if (weekday != null) {
				return weekday.isWeekday();
			} else {
				return DateUtil.isWeekday(date);
			}
		} finally {
			dbAdapter.close();
		}
	}

	@Override
	public List<Weekday> listWeekday(Date from, Date to) {
		if (from == null) {
			throw new IllegalArgumentException("Argument 'from' is NULL!");
		}
		if (to == null) {
			throw new IllegalArgumentException("Argument 'to' is NULL!");
		}

		try {
			dbAdapter.open();
			List<Weekday> resultList = new LinkedList<Weekday>();
			Map<Date, Weekday> dbMap = dbAdapter.fetchWeekdayMap(from, to);

			Calendar fromCal = DateUtil.getCalendar(from);
			Calendar toCal = DateUtil.getCalendar(to);

			for (; fromCal.compareTo(toCal) < 0; fromCal.add(Calendar.DATE, 1)) {
				if (dbMap.containsKey(fromCal.getTime())) {
					resultList.add(dbMap.get(fromCal.getTime()));
				} else {
					Weekday weekday = new Weekday(fromCal.getTime(),
							DateUtil.isWeekday(fromCal), null, null);
					resultList.add(weekday);
				}
			}
			return resultList;
		} finally {
			dbAdapter.close();
		}
	}

	@Override
	public List<Map<String, String>> asSimpleAdapterData(Context cxt,
			List<Weekday> list) {
		List<Map<String, String>> result = new LinkedList<Map<String, String>>();
		for (Weekday wk : list) {
			Map<String, String> map = new HashMap<String, String>();

			map.put(DbAdapter.KEY_DATE, DateUtil.formatWithWeek(wk.getDate()));
			String isWeekdayStr = wk.isWeekday() ? cxt.getResources()
					.getString(R.string.label_weekday) : cxt.getResources()
					.getString(R.string.label_holiday);
			map.put(DbAdapter.KEY_IS_WEEKDAY, isWeekdayStr);
			map.put(DbAdapter.KEY_TYPE, wk.getType());
			map.put(DbAdapter.KEY_DESC, wk.getDesc());

			result.add(map);
		}
		return result;
	}
}
